<template>
  <div class="container">
    <el-card>
      <template #header>
        <span>试题录入</span>
      </template>
      <!-- 表单区域 -->
      <el-form
        :model="newForm"
        :rules="rules"
        ref="newForm"
        label-width="100px"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            @change="getSimpleDirectorys"
            v-model="newForm.subjectID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="newForm.catalogID" placeholder="请选择">
            <el-option
              v-for="item in directoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="newForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="city-item" label="城市：" required>
          <el-col :span="3">
            <el-form-item prop="province">
              <el-select
                @change="getCityList"
                v-model="newForm.province"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in provincesList"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" class="inline">
            <el-form-item prop="city">
              <el-select
                v-model="newForm.city"
                collapse-tags
                style="margin-left: 4px"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in cityList"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="newForm.direction" placeholder="请选择">
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="newForm.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="newForm.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="quill" label="题干：" prop="question">
          <!-- 富文本框 -->
          <quillEditor :options="options" v-model="newForm.question" />
        </el-form-item>
        <!-- 选项区域  单选or复选 -->
        <!-- 单选题 -->
        <el-form-item
          v-if="!newForm.questionType || newForm.questionType === '1'"
          label="选项："
          class="option"
        >
          <!-- 单选 -->
          <el-row
            class="radio-item"
            v-for="item in newForm.options"
            :key="item.code"
          >
            <el-radio v-model="radio" :label="item.code">
              <span>{{ item.code }}：</span>
              <el-input
                v-model="item.title"
                size="mini"
                class="radio-input"
              ></el-input>
            </el-radio>
            <!-- 头像上传 -->
            <el-upload
              class="uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
            >
              <template #trigger>
                <p>上传图片</p>
              </template>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </el-row>
        </el-form-item>
        <!-- 多选题 -->
        <el-form-item
          v-if="newForm.questionType === '2'"
          label="选项："
          class="option"
        >
          <el-row
            class="checkbox-item"
            v-for="(item, index) in newForm.options"
            :key="index"
          >
            <el-checkbox v-model="checkbox" :label="item.code">
              <span>{{ item.code }}：</span>
              <el-input
                v-model="item.title"
                size="mini"
                class="radio-input"
              ></el-input>
            </el-checkbox>
            <!-- 头像上传 -->
            <el-upload
              class="uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
            >
              <template #trigger>
                <p>上传图片</p>
              </template>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </el-row>
        </el-form-item>
        <!-- 增加选项与答案按钮 -->
        <el-form-item>
          <el-button
            @click="addOptipn"
            v-if="newForm.questionType !== '3'"
            :disabled="!newForm.questionType || newForm.questionType === '1'"
            type="danger"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：">
          <el-input class="video-input" v-model="newForm.videoURL"></el-input>
        </el-form-item>
        <el-form-item class="quill" label="答案解析：" prop="answer">
          <!-- 富文本框 -->
          <quillEditor :options="options" v-model="newForm.answer" />
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注：">
          <el-input
            type="textarea"
            :rows="4"
            class="video-input"
            v-model="newForm.remarks"
          ></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <el-select
            multiple
            v-model="newForm.tags"
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 底部按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入api
import { simpleSub } from '@/api/hmmm/subjects.js'
import { simpleDirectorys } from '@/api/hmmm/directorys.js'
import { list } from '@/api/hmmm/companys.js'
import { simpleTags } from '@/api/hmmm/tags.js'
import { add, detail } from '@/api/hmmm/questions.js'
// 导入城市数据
import { provinces, citys } from '@/api/hmmm/citys.js'
const options = {
  placeholder: '请输入文章内容',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
      [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
      ['blockquote', 'code-block'], // 引用，代码块
      ['image', 'link'] // 链接、图片、视频-----['link', 'image', 'video']
    ]
  }
}
export default {
  name: 'QuestionsNew',
  data () {
    return {
      checkbox: [],
      radio: '',
      // 富文本框配置项
      options: options,
      // 方向列表
      directionList: [
        'o2o',
        '外包服务',
        '企业服务',
        '互联网金融',
        '企业咨询',
        '互联网',
        '电子商务',
        '其他'
      ],
      // 标签列表
      tagsList: [],
      // 地区列表
      cityList: [],
      // 市级列表
      provincesList: [],
      // 企业列表
      companyList: [],
      // 目录列表
      directoryList: [],
      // 学科列表
      subjectList: [],
      // 表单数据
      newForm: {
        answer: null,
        catalogID: null,
        city: null,
        province: null,
        direction: null,
        difficulty: null,
        enterpriseID: null,
        options: [
          {
            code: 'A',
            title: '',
            img: null,
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: null,
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: null,
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: null,
            isRight: false
          }
        ],
        question: null,
        questionType: null,
        remarks: null,
        subjectID: null,
        tags: null,
        videoURL: null
      },
      // 表单校验
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      }
    }
  },
  components: { quillEditor },
  created () {
    this.initList()
    this.provincesList = provinces()
    this.dataShow()
  },
  // 不用watch监听，点击提交发送请求之前调用也可以
  watch: {
    radio (val) {
      this.setRadioTrue(val)
    },
    checkbox (val) {
      this.setCheckBox(val)
    }
  },
  methods: {
    // 初始化数据  学科列表&企业列表
    async initList () {
      try {
        const { data } = await simpleSub()
        const {
          data: { items }
        } = await list({
          pagesize: 10000000
        })
        this.subjectList = data
        this.companyList = items
      } catch (e) {
        console.log(e)
      }
    },
    // 根据学科列表获取目录列表&&标签列表
    async getSimpleDirectorys (subjectID) {
      this.newForm.catalogID = null
      this.newForm.tags = null
      try {
        const { data } = await simpleDirectorys({ subjectID })
        console.log(data)
        const { data: tagsList } = await simpleTags({ subjectID })
        this.directoryList = data
        this.tagsList = tagsList
        this.newForm.catalogID = this.directoryList[0]?.value
      } catch (e) {
        console.log(e)
      }
    },
    // 获取地区列表
    getCityList (province) {
      this.cityList = citys(province)
      this.newForm.city = this.cityList[0]
    },
    // 选项单选功能
    setRadioTrue (val) {
      this.newForm.options.forEach((item) => (item.isRight = false))
      const index = this.newForm.options.findIndex((item) => item.code === val)
      this.newForm.options[index].isRight = true
    },
    // 点击增加选项和答案按钮
    addOptipn () {
      const enList = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N'
      ]
      const en = this.newForm.options[this.newForm.options.length - 1].code
      const index = enList.findIndex((i) => i === en)
      const code = enList[index + 1]
      this.newForm.options.push({
        code,
        title: '',
        img: null,
        isRight: false
      })
    },
    // 选项多选功能
    setCheckBox (val) {
      this.newForm.options.forEach((item) => {
        item.isRight = false
      })
      val.forEach((code) => {
        this.newForm.options.forEach((item) => {
          if (item.code === code) {
            item.isRight = true
          }
        })
      })
      console.log(this.newForm.options)
    },
    // 点击确认提交按钮
    async submitForm () {
      await this.$refs.newForm.validate()
      try {
        await add(this.newForm)
        this.$refs.newForm.resetFields()
        this.$message.success('试题添加成功')
        this.$router.replace('list')
      } catch (e) {
        this.$message.error('试题添加失败')
      }
    },
    // 数据回显
    async dataShow () {
      const id = this.$route.query.id
      if (id) {
        const { data } = await detail({ id })
        const { subjectID } = data
        const { data: list } = await simpleDirectorys({ subjectID })
        this.directoryList = list
        this.newForm = data
      }
    }
  }
}
</script>

<style scoped lang="less">
.el-card {
  margin: 20px;
}
.el-select,
.video-input {
  width: 400px;
}
.city-item {
  .el-select {
    width: 198px;
  }
}
.quill {
  height: 270px;
  ::v-deep .ql-editor {
    height: 200px;
  }
}
.el-radio,
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.radio-item,
.checkbox-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.radio-input {
  width: 240px;
}
.uploader {
  // position: absolute;
  // right: -75px;
  // top: -15px;
  position: relative;
  width: 100px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  line-height: 60px;
  text-align: center;
  p {
    margin: 0;
    padding: 0;
    width: 100px;
    // height: 60px;
    // line-height: 60px;
  }
}
.uploader:hover {
  border-color: #409eff;
}
.option {
  .el-radio,
  .el-checkbox {
    margin-bottom: 40px;
  }
}
.el-icon-circle-close {
  position: absolute;
  right: -10px;
  top: -10px;
  font-size: 18px;
}
.inline {
  margin-left: 5px;
}
</style>
